package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDTO;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;

import com.sky.service.AddressBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void save(AddressBookDTO addressBookDTO) {

        AddressBook addressBook = AddressBook.builder().build();
        BeanUtils.copyProperties(addressBookDTO, addressBook);

        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);

        addressBookMapper.insert(addressBook);

    }

    @Override
    public List<AddressBook> list() {

        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookMapper.getByUserId(userId);

        return addressBookList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByDefault(AddressBook addressBook) {

        //先把改用户的地址全部变为非默认
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateByUserId(addressBook);

        //将制定id的地址设置为默认
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);

    }

    @Override
    public AddressBook getById(Long id) {

        return addressBookMapper.getById(id);

    }

    @Override
    public AddressBook getByDefault() {

        AddressBook addressBook = AddressBook.builder().build();

        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);

        return addressBookMapper.getByDefault(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public void updateAddress(AddressBookDTO addressBookDTO) {

        AddressBook addressBook = AddressBook.builder().build();
        BeanUtils.copyProperties(addressBookDTO, addressBook);

        addressBookMapper.updateById(addressBook);

    }

}
